﻿using AuthCenter.Api.Write.Application.Command.Menu;
using AuthCenter.Application;
using AuthCenter.Domain;
using AuthCenter.ErrorCode;
using AutoMapper;
using MediatR;
using System.Transactions;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace AuthCenter.Api.Write.Application.Hander.Menu
{
    public class DeleteMenuHander : IRequestHandler<DeleteMenuCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<MenuModel> _menuRepository;
        private readonly IMapper _mapper;
        public DeleteMenuHander(IBaseRepository<MenuModel> menuRepository, IMapper mapper)
        {
            _menuRepository = menuRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(DeleteMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            var model = _menuRepository.GetAll().Where(x => x.Id == request.Id).FirstOrDefault();
            if (model == null)
            {
                res.Code = ApiEnums.Error;
                res.Message = "菜单不存在";
            }
            int t = 0;
            int t1 = 0;
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                void DeleteMenu(long id)
                {
                    var children = _menuRepository.GetAll().Where(x => x.PId == id && !x.IsDeleted).ToList();
                    foreach (var child in children)
                    {
                        DeleteMenu(child.Id);
                        child.IsDeleted = true;
                        t1 = _menuRepository.Update(child);
                    }
                }
                DeleteMenu(model.Id);
                model.IsDeleted = true;
                t = _menuRepository.Update(model);
                tran.Complete();
                res.Code = ApiEnums.OK;
                res.Message = "删除成功";
                res.Data = t;
                return Task.FromResult(res);
            }
        }
    }
}
